package com.android.delivery.activity.fragment

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.android.delivery.App
import com.android.delivery.R
import com.android.delivery.activity.LanJianZhongXinActivity
import com.android.delivery.activity.OrderSettleActivity
import com.android.delivery.activity.PeiSongZhongXinActivity
import com.android.delivery.activity.SendSoonListActivity
import com.android.delivery.activity.siji.CaptureActivity
import com.android.delivery.activity.wangdian.CityAcceptFragment
import com.android.delivery.activity.wangdian.DaiJieCheListFragment
import com.android.delivery.activity.wangdian.HistoryOrderActivity
import com.android.delivery.activity.wangdian.RiderManagementActivity
import com.android.delivery.adapter.BaseFragmentStateAdapter
import com.android.delivery.adapter.wangdian.NetProgressAdapter
import com.android.delivery.api.ApiService
import com.android.delivery.base.LazyFragment
import com.android.delivery.callback.DialogCallback
import com.android.delivery.callback.LzyResponse
import com.android.delivery.constant.Constants
import com.android.delivery.entity.NetHome
import com.android.delivery.entity.even.RefreshUserEvent
import com.android.delivery.util.DensityUtil
import com.android.delivery.util.GlideUtil
import com.android.delivery.util.StringUtils
import com.android.delivery.util.print.ListUtils
import com.google.android.material.appbar.AppBarLayout
import com.lzy.okgo.model.Response
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.tbruyelle.rxpermissions3.RxPermissions
import com.wuhenzhizao.sku.utils.ScreenUtils
import kotlinx.android.synthetic.main.fragment_wangdian.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class WangDianFragment : LazyFragment() {

    private val mTitles: MutableList<String> = ArrayList()
    private val tabFragmentList: MutableList<Fragment> = ArrayList()
    private var netProgressAdapter: NetProgressAdapter? = null

    override fun initViews(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_wangdian, container, false)
    }

    override fun initData() {
    }

    override fun lazyInit() {
        mTitles.add("待接单")
        mTitles.add("待接车")
        mTitles.add("同城已接单")

        tabFragmentList.add(DaiJieDanListFragment.newInstance())
        tabFragmentList.add(DaiJieCheListFragment.newInstance())
        tabFragmentList.add(CityAcceptFragment.newInstance())

        val statusBarHeight = ScreenUtils.getStatusBarHeight(activity)
        layout_info.setPadding(0, statusBarHeight, 0, DensityUtil.dp2px(12f))
        view_pager.setAdapter(BaseFragmentStateAdapter(fragmentManager, tabFragmentList, mTitles))
        tab_layout.setupWithViewPager(view_pager) //此方法就是让tablayout和ViewPager联动

        refreshLayout_header.setColorSchemeColors(resources.getColor(R.color.colorAccent))
        refreshLayout.setEnableLoadMore(false)
        refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                getHomeData()

                onRefreshFragment()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

        })

        netProgressAdapter = NetProgressAdapter()
        val linearLayoutManager = LinearLayoutManager(activity)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        net_pb_rv.layoutManager = linearLayoutManager
        net_pb_rv.adapter = netProgressAdapter

        tv_ljzx.setOnClickListener {
            val intent = Intent(context, LanJianZhongXinActivity::class.java)
            startActivity(intent)
        }

        tv_sweep_down.setOnClickListener {
            RxPermissions(this).request(Manifest.permission.CAMERA).subscribe { aBoolean ->
                if (aBoolean) {
                    val intent = Intent(activity, CaptureActivity::class.java)
                    intent.putExtra(Constants.TYPE, CaptureActivity.TYPE_SCAN_OFF_CAR)
                    startActivity(intent)
                }
            }
        }

        ll_dlj.setOnClickListener {
            val intent = Intent(context, LanJianZhongXinActivity::class.java)
            startActivity(intent)
        }

        ll_ylj.setOnClickListener {
            val intent = Intent(context, LanJianZhongXinActivity::class.java)
            intent.putExtra(Constants.TYPE, 1)
            startActivity(intent)
        }

        ll_jrdd.setOnClickListener {
            val intent = Intent(context, SendSoonListActivity::class.java)
            startActivity(intent)
        }

        tv_pszx.setOnClickListener {
            val intent = Intent(context, PeiSongZhongXinActivity::class.java)
            startActivity(intent)
        }

        tv_qsgl.setOnClickListener {
            var intent = Intent(context, RiderManagementActivity::class.java)
            startActivity(intent)
        }

        tv_spjj.setOnClickListener {
            var intent = Intent(context, OrderSettleActivity::class.java)
            intent.putExtra(Constants.TYPE, OrderSettleActivity.TYPE_SEND)
            startActivity(intent)
        }

        tv_ldjj.setOnClickListener {
            var intent = Intent(context, OrderSettleActivity::class.java)
            intent.putExtra(Constants.TYPE, OrderSettleActivity.TYPE_LINDAN_SEND)
            startActivity(intent)
        }

        tv_lsdd.setOnClickListener {
            var intent = Intent(context, HistoryOrderActivity::class.java)
            startActivity(intent)
        }

        iv_scan.setOnClickListener {
            RxPermissions(this).request(Manifest.permission.CAMERA).subscribe { aBoolean ->
                if (aBoolean) {
                    val intent = Intent(activity, CaptureActivity::class.java)
                    intent.putExtra(Constants.TYPE, CaptureActivity.TYPE_SCAN_DISPATCH)
                    startActivity(intent)
                }
            }
        }
        iv_scan_toolbar.setOnClickListener {
            RxPermissions(this).request(Manifest.permission.CAMERA).subscribe { aBoolean ->
                if (aBoolean) {
                    val intent = Intent(activity, CaptureActivity::class.java)
                    intent.putExtra(Constants.TYPE, CaptureActivity.TYPE_SCAN_DISPATCH)
                    startActivity(intent)
                }
            }
        }

        toolbar.layoutParams.height = statusBarHeight + DensityUtil.dp2px(44f)
        toolbar.setPadding(0, statusBarHeight, 0, 0)
        appBar.addOnOffsetChangedListener(object : AppBarLayout.OnOffsetChangedListener {
            override fun onOffsetChanged(appBarLayout: AppBarLayout?, offset: Int) {
                var alpha = offset / layout_info.height.toFloat()
                if (alpha > 1) {
                    alpha = 1.0f
                }
                toolbar.alpha = (Math.abs(alpha))

                if (offset >= 0) {
                    setEnableRefresh(true)
                } else {
                    setEnableRefresh(false)
                }
            }

        })

        initUserInfo()

        getHomeData()
    }

    private fun onRefreshFragment() {
        if (!ListUtils.isEmpty(tabFragmentList)){
            val fragment = tabFragmentList.get(view_pager.currentItem)
            if (fragment != null){
                if (fragment is DaiJieDanListFragment) {
                    (fragment as DaiJieDanListFragment).onAutoRefresh()
                } else if (fragment is DaiJieCheListFragment) {
                    (fragment as DaiJieCheListFragment).onAutoRefresh()
                }else if (fragment is CityAcceptFragment) {
                    (fragment as CityAcceptFragment).onAutoRefresh()
                }
            }
        }
    }

    fun finishRefresh(){
        refreshLayout?.finishRefresh()
    }

    /**
     * 获取首页数据
     */
    private fun getHomeData() {
        ApiService.getNetHome(this, object : DialogCallback<LzyResponse<NetHome>>() {
            override fun onSuccess(response: Response<LzyResponse<NetHome>>) {
                refreshLayout.finishRefresh()
                val netHome = response.body().data
                if (netHome != null) {
                    tv_dlj.setText(netHome.waitSignQuantity.toString())
                    tv_ylj.setText(netHome.pickQuantity.toString())
                    tv_jrdd.setText(netHome.transportingQuantity.toString())
                    tv_curr.setText(netHome.standardQuantity.toString())

                    val logisticsAwardTemplateList = netHome.logisticsAwardTemplateList
                    if (logisticsAwardTemplateList != null) {
                        val last = logisticsAwardTemplateList.last()
                        var progress = netHome.standardQuantity * 100 / last.target
                        val layoutParams = line.layoutParams as ConstraintLayout.LayoutParams
                        var pbWidth = ScreenUtils.getScreenWidth(activity) - DensityUtil.dp2px(48f)
                        var marginLeft = pbWidth * progress / 100
                        var dp_10 = DensityUtil.dp2px(10f)
                        if (marginLeft < dp_10) {
                            marginLeft = dp_10
                        }
                        layoutParams.setMargins(marginLeft, 0, 0, 0)
                        net_pb.setProgress(progress)
                        netProgressAdapter?.setMaxProgress(last.target)
                        netProgressAdapter?.setNewData(logisticsAwardTemplateList)
                    }
                }

            }

            override fun onError(response: Response<LzyResponse<NetHome>>?) {
                super.onError(response)

                refreshLayout.finishRefresh()
            }
        })
    }

    private fun setEnableRefresh(enableRefresh: Boolean) {
        for (fragment in tabFragmentList) {
            if (fragment is DaiJieDanListFragment) {
                (fragment as DaiJieDanListFragment).setEnableRefresh(enableRefresh)
            } else if (fragment is DaiJieCheListFragment) {
                (fragment as DaiJieCheListFragment).setEnableRefresh(enableRefresh)
            }
        }
    }

    private fun initUserInfo() {
        val loginInfo = App.getInstance()?.getLoginInfo()
        if (loginInfo != null) {
            GlideUtil.loadCircleImg(iv_photo, loginInfo.user?.avatar)
            tv_name.setText(loginInfo.user?.nickname)
            tv_phone.setText(StringUtils.getFormatPhone(loginInfo.user?.mobile))

            GlideUtil.loadCircleImg(iv_photo_toolbar, loginInfo.user?.avatar)
            tv_name_toolbar.setText(loginInfo.user?.nickname)
            tv_phone_toolbar.setText(StringUtils.getFormatPhone(loginInfo.user?.mobile))
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun addrEven(item: RefreshUserEvent) {
        initUserInfo()
    }

    override fun isBindEventBus(): Boolean {
        return true
    }
}